package main

import (
	"fmt"
	"time"
)

func sendData(ch chan string, id int) {
	for i := 0; i < 3; i++ {
		fmt.Printf("SEND: [%d]:[%d]\n", id, i)
		ch <- fmt.Sprintf("[%d]:[%d]", id, i)
	}
	close(ch) // 关闭通道
}

func main() {
	ch1 := make(chan string, 3)
	ch2 := make(chan string, 3)

	go sendData(ch1, 1)
	go sendData(ch2, 2)

	receivedCount := 0 // 计数器，记录已接收的消息数量

	for {
		select {
		case msg, ok := <-ch1:
			if !ok {
				time.Sleep(500 * time.Millisecond)
				continue
			}
			fmt.Println("RECV ch1:", msg)
			time.Sleep(1000 * time.Millisecond) // 模拟一些延迟
			fmt.Println("RECV ch1 END")
			receivedCount++
		case msg, ok := <-ch2:
			if !ok {
				time.Sleep(500 * time.Millisecond)
				continue
			}
			fmt.Println("RECV ch2:", msg)
			time.Sleep(1000 * time.Millisecond) // 模拟一些延迟
			fmt.Println("RECV ch2 END")
			receivedCount++
		default:
			if receivedCount >= 6 { // 一共应该接收到 6 条消息
				fmt.Println("All messages received, exiting.")
				return
			}
			fmt.Println("default:---")
			time.Sleep(100 * time.Millisecond) // 避免忙等
		}
	}
}
